<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import {ElMessage, ElMessageBox} from 'element-plus'
import { Table } from '@/components/Table'
import { delTableListApi } from '@/api/table'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas  } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import {RecordType} from "@/api/record/types";
import {formatToDateTime} from "@/utils/dateUtil";
import {useValidator} from "@/hooks/web/useValidator";
import {CreatePictureClassForm, EditPictureClassForm, PictureClassType} from "@/api/pictureClass/types";
import {createPictureClassApi, deletePictureClassApi, editPictureClassApi, pictureClassApi} from "@/api/pictureClass";

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await pictureClassApi()
    return {
      list: res.data,
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose } = tableMethods

const setSearchParams = (formData: any) => {
  getList()
}
const {required} = useValidator()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: "ID",
    form:{
      hidden: true,
    },
    table: {
      width: 80,
    }
  },
  {
    field: 'created_at',
    label: '创建时间',
    table: {
      width: 180,
      slots: {
        default: (scope: any)=>{
          const row = scope.row as RecordType
          const time = formatToDateTime(row.created_at, "YYYY-MM-DD hh:mm:ss")
          return <span>{time}</span>
        }
      }
    },
    form: {
      hidden: true
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'name',
    label: '类型名称',
    form: {
      colProps: {
        span: 15
      },
      formItemProps: {
        rules: [required()],
      }
    },
  },
  {
    field: 'sort',
    label: "排序",
    form: {
      component: "InputNumber",
      componentProps: {
        min: 0
      }
    }
  },
  {
    field: 'action',
    width: '200px',
    label: '操作',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      width: 200,
      slots: {
        default: (data: any) => {
          const row = data.row as PictureClassType
          return (
            <>
              <BaseButton type="primary" onClick={() => action(data.row, 'edit')} roles={[99]}>
                编辑
              </BaseButton>
              <BaseButton type="danger" onClick={()=>delData(row)}>删除</BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<UserType | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = '新增用户'
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const delLoading = ref(false)

const delData = async (row: PictureClassType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  await ElMessageBox.confirm("确认删除选中的记录吗,删除后所有分类下的图片将无法查看，请谨慎操作！", "提示")
  delLoading.value = true
  const promises: Promise<any>[] = []
  unref(ids).forEach(id=>{
    promises.push(deletePictureClassApi(parseInt(id)))
  })
  await Promise.all(promises).finally(()=>delLoading.value = false)
  // 删除完成
  ElMessage.success('删除完成')
  tableMethods.refresh()
}

const action = (row: PictureClassType, type: string) => {
  dialogTitle.value = type === 'edit' ? '编辑类型' : '类型详情'
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const salt = import.meta.env.VITE_SALT
    const params: CreatePictureClassForm = {
      sort: formData.sort,
      name: formData.name,
    }
    if (actionType.value === 'edit'){
      const e_params: EditPictureClassForm = {
        id: currentRow.value.id,
        ...params
      }
      await editPictureClassApi(e_params).finally(()=>saveLoading.value = false)
      ElMessage.success("修改用户成功")
    }else{
      await createPictureClassApi(params)
          .finally(() => {
            saveLoading.value = false
          })
      ElMessage.success("新增用户成功")
    }
    dialogVisible.value = false
    currentPage.value = 1
    getList()
  }
}
const switchStatus = async(user: UserType)=>{
  await userDisableApi({
    disable: !user.is_disabled,
    id: user.id
  })
  ElMessage.success("操作成功")
  tableMethods.refresh()
}
</script>

<template>
  <ContentWrap title="图片类型">
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" v-if="false"/>

    <div class="mb-10px">
      <BaseButton :loading="delLoading" type="primary" @click="AddAction()"  :roles="[99]">
        新增类型
      </BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)"  :roles="[99]">
        删除
      </BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        保存
      </BaseButton>
      <BaseButton @click="dialogVisible = false">关闭</BaseButton>
    </template>
  </Dialog>
</template>
